package com.puzzlebazar.client.squaregrid.control;

import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.MouseEvent;
import com.google.gwt.event.shared.EventHandler;
import com.puzzlebazar.client.puzzle.model.History;
import com.puzzlebazar.client.puzzle.model.MoveTimer;
import com.puzzlebazar.client.squaregrid.model.StateModel;
import com.puzzlebazar.client.util.Vec2i;

public class CellStateCycleControl extends CellStateControl {

	
	/**
	 * Implements a "cycling-control" feel. (Left button = increments state, 
	 * right button = decrements state.)
	 * 
	 * @param stateModel The model to control 
	 * @param history  The history track to control (null if no history is desired)
	 * @param moveTimer The timer model to extract the time at which the move have been performed
	 */
	public CellStateCycleControl( StateModel stateModel, History history, MoveTimer moveTimer ) {
		super(stateModel, history, moveTimer);
	}

	@Override
	public int stateToGenerate( Vec2i loc, MouseEvent<? extends EventHandler> event  ) throws Exception {
		
		int dir = 1;
		if( event.getNativeButton() == NativeEvent.BUTTON_RIGHT ) {
			dir = dir * -1;
		}
		if( event.isShiftKeyDown() ) {
			dir = dir * -1;
		}
		return cycleState(loc, dir );
	}


	/**
	 * Cycle through events
	 * 
	 * @param loc Location of the clicked cell
	 * @param dir Direction into which to cycle
	 * @return The new state
	 * @throws Exception
	 */
	private int cycleState(Vec2i loc, int dir) throws Exception {
		try {
			int nbStates = getNbStates();
			int newState = (getState( loc ) + dir + nbStates) % nbStates;
			return newState;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	@Override
	public void release() {
		super.release();
	}
	
	
}